package com.example.wan1.view.user;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.wan1.R;
import com.example.wan1.base.activity.RootActivity;
import com.example.wan1.base.activity.SimpleActivity;
import com.example.wan1.base.adapter.BaseFragmentPagerAdapter;
import com.example.wan1.base.adapter.SubPagerAdapter;
import com.example.wan1.base.injection.InjectPresenter;
import com.example.wan1.bus.RxBus;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.CoinBean;
import com.example.wan1.model.UserBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.model.common.CommonResMultiList;
import com.example.wan1.utils.ColorTheme;
import com.example.wan1.utils.StatusBarCompat;
import com.example.wan1.utils.StatusBarUtil;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.collect.PerCollectFragment;
import com.example.wan1.view.login.UserManager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import javax.inject.Inject;

import butterknife.BindView;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

/***
 * 用户中心
 * 1.如果跳转的时候是分享类型的，那么就跳到这里
 */
public class UserCenterActivity extends SimpleActivity implements AppBarLayout.OnOffsetChangedListener,
        UserCenterContract.View {

    @BindView(R.id.iv_parallax)
    ImageView ivParallax;
    @BindView(R.id.user_toolbar)
    Toolbar mToolBar;
    //toolbar1 状态栏卡住 tablayout 不向上滑动
    @BindView(R.id.toolbar1)
    Toolbar mToolBar1;

    @BindView(R.id.tv_nickname)
    TextView tvNickName;
    @BindView(R.id.tv_toolbar_name)
    TextView tvTbNickName;
    @BindView(R.id.tv_user_center_rank)
    TextView tvUserCenterRank;
    @BindView(R.id.tv_user_center_coin)
    TextView tvUserCenterCoin;
    @BindView(R.id.collection_tab)
    TabLayout mCollectionTab;
    @BindView(R.id.collection_view_pager)
    ViewPager mViewPager;

    @BindView(R.id.sr_refresh)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.appbar_layout)
    AppBarLayout mAppbarLayout;
    @BindView(R.id.collapse)
    CollapsingToolbarLayout mCollapsingToolbarLayout;

    @Inject
    UserCenterPresenter mPresenter;

    private int id;//用户id
    private String pageType;//跳转类型
    private int page = 1;

    List<String> mTitle;
    List<Fragment> mFragments;

    private int mOffset = 0;
    private int mScrollY = 0;

    private BaseFragmentPagerAdapter mAdapter;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_user_center;
    }

    @Override
    protected void initData() {
        //mPresenter.getShareList(id, page);
    }

    @Override
    protected void initView() {
        mTitle = new ArrayList<>();
        mFragments = new ArrayList<>();
        id = getIntent().getIntExtra("id", -1);

        mToolBar.setNavigationOnClickListener(v -> finish());
        // 状态栏透明并加入状态栏宽度
        StatusBarUtil.setTranslucentForImageView(this, 0, mToolBar);
        StatusBarUtil.setTranslucentForImageView(this, 0, mToolBar1);
        //刷新的逻辑
        refreshListener();
        mAppbarLayout.addOnOffsetChangedListener(this);
        mToolBar.setBackgroundColor(0);

        //userId在广场列表中有，不用修改db
        //在这里可以通过id等不等于-1，来判断是不是自己的页面还是其他分享人的界面
        // 如果是其他的分享人，应该是请求数据的接口是错误的

        /*if (Constants.SQUARE_USER_TYPE.equals(pageType)) {
            ToolsUtils.setIndicatorWidth(mCollectionTab, getResources().getDimensionPixelSize(R.dimen.dp_30));
            mTitle.add(getString(R.string.share_article_text));
            mFragments.add(PerCollectFragment.newInstance(Constants.SQUARE_USER_TYPE, userId));
            mCollectionTab.setTabMode(TabLayout.MODE_SCROLLABLE);
            mPresenter.getUserShareArticlesData(userId, 1);
        } else {
            tvNickName.setText(mPresenter.getLoginUserName());
            tvTbNickName.setText(mPresenter.getLoginUserName());
            mTitle.add(getString(R.string.collection_article));
            mTitle.add(getString(R.string.share_article_text));
            mTitle.add(getString(R.string.collection_web));
            mFragments.add(CollectionFragment.newInstance(Constants.COLLECTION_NOT_REFRESH_TYPE));
            mFragments.add(PrivateArticleFragment.newInstance("", -1));
            mFragments.add(CollectionWebFragment.newInstance(Constants.COLLECTION_NOT_REFRESH_TYPE));
            //下划线间距
            ToolsUtils.setIndicatorWidth(mCollectionTab, getResources().getDimensionPixelSize(R.dimen.dp_30));
            mPresenter.getCoinAndRank();
        }
        mAdapter = new HomeTabPageAdapter(getSupportFragmentManager(), mTitle, mFragments);
        mViewPager.setAdapter(mAdapter);
        mCollectionTab.setupWithViewPager(mViewPager);*/
        Log.i("zxd", "initView111: " + id);
        if (id == -1) {
            UserBean user = UserManager.getInstance().getUser();
            tvNickName.setText(user.getUsername());
            tvTbNickName.setText(user.getUsername());
            tvUserCenterRank.setText("lv " + user.getLevel());
            tvUserCenterCoin.setText("积分：" + user.getCoinCount());
            mTitle.add(getString(R.string.collect_article_title));
            mTitle.add(getString(R.string.collect_web_title));
            mTitle.add(getString(R.string.collect_share_title));
            mFragments.add(new PerCollectFragment().newInstance(getString(R.string.collect_article_title), true));
            mFragments.add(new PerCollectFragment().newInstance(getString(R.string.collect_web_title), true));
            mFragments.add(new PerCollectFragment().newInstance(getString(R.string.collect_share_title), true));
            //下划线间距
            ToolsUtils.setIndicatorWidth(mCollectionTab, getResources().getDimensionPixelSize(R.dimen.dp_30));
        } else {
            tvNickName.setText(getIntent().getStringExtra("username"));
            tvTbNickName.setText(getIntent().getStringExtra("username"));
            tvUserCenterRank.setText("lv ?");
            tvUserCenterCoin.setText("积分：?");
            ToolsUtils.setIndicatorWidth(mCollectionTab, getResources().getDimensionPixelSize(R.dimen.dp_30));
            mTitle.add(getString(R.string.share_article_text));
            mFragments.add(new PerCollectFragment().newInstance(getString(R.string.collect_share_title), true, id));
            mCollectionTab.setTabMode(TabLayout.MODE_SCROLLABLE);
            mPresenter.getShareList(id, page);
        }
//        mAdapter = new SubPagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
//        mAdapter.setData(mFragments, mTitle);
        mAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mFragments);
        mViewPager.setAdapter(mAdapter);
        mCollectionTab.setupWithViewPager(mViewPager);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mCollectionTab.setElevation(0);
        }
        for (int i = 0; i < mTitle.size(); i++) {
            mCollectionTab.getTabAt(i).setText(mTitle.get(i));
        }
        //设置toolbar的颜色
        int color = ToolsUtils.getThemeColor(this);
        if (color != 0) {
            mCollectionTab.setSelectedTabIndicatorColor(color);
            mCollectionTab.setTabTextColors(Color.parseColor("#333333"), color);
            ColorDrawable colorDrawable = new ColorDrawable(color);
            mCollapsingToolbarLayout.setContentScrim(colorDrawable);
        }
    }

    @Override
    public void onSuccess(CommonResMultiList<CoinBean, CommonResList<ArticleBean>> data) {
        page = data.getData2().getCurPage() + 1;
        tvUserCenterRank.setText("lv " + data.getData1().getLevel());
        tvUserCenterCoin.setText("积分：" + data.getData1().getCoinCount());
    }

    @Override
    public void onFailure(String msg) {
        ToastUtils.showToast(msg);
    }

    //头图 toolbar 动效处理
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        //获取最大偏移值
        int scrollRangle = appBarLayout.getTotalScrollRange();
        ivParallax.setTranslationY(verticalOffset);
        /**
         * 这个数值可以自己定义 显示 toolbar 用户名称
         */
        if (verticalOffset < -250) {
            tvTbNickName.setVisibility(View.VISIBLE);
        } else {
            tvTbNickName.setVisibility(View.GONE);
        }
        int mAlpha = (int) Math.abs(255f / scrollRangle * verticalOffset);
        int color = ContextCompat.getColor(appBarLayout.getContext(), R.color.colorPrimary) & 0x00ffffff;
        color = ToolsUtils.getThemeColor(this) != 0 ? ToolsUtils.getThemeColor(this) & 0x00ffffff : color;
        StatusBarUtil.setColorNoTranslucentLightMode(this, ((mAlpha) << 24) | color);
        //顶部title渐变效果
        mToolBar.setBackgroundColor(((mAlpha) << 24) | color);
    }

    private void refreshListener() {
        mSmartRefreshLayout.setOnMultiListener(new SimpleMultiListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(2000);
                //这里需要发送事件，让碎片进行刷新
                RxBus.getDefault().post("refreshAll");
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //加载的逻辑放到fragment碎片中进行处理
                /*refreshLayout.finishLoadMore(2000);
                mAdapter.setType(Constants.LOAD_MORE_TYPE);
                mAdapter.notifyDataSetChanged();
                ToolsUtils.setIndicatorWidth(mCollectionTab, getResources().getDimensionPixelSize(R.dimen.dp_30));*/
            }

            //处理头部下拉刷新
            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                mOffset = offset / 2;
                ivParallax.setTranslationY(mOffset - mScrollY);
                mToolBar.setAlpha(1 - Math.min(percent, 1));
            }
        });
    }
}
